import React, { Component, PropTypes } from 'react'
import classnames from 'classnames'
import SiteInput from './SiteInput'

class SiteItem extends Component {
    constructor(props, context) {
        super(props, context)
        this.state = { editing: false }
    }

    handleEditActive() {
        this.setState({ editing: true })
    }

    handleSave(id, text) {
        if (text.length != 0) {
            this.props.editRefSite(id, text, this.props.gid)
        }
        this.setState({ editing: false })
    }

    render() {
        const { gid, site, deleteRefSite } = this.props

        let element
        if (this.state.editing) {
            element = (
                <SiteInput text={site.text}
                    onSave={(text) => this.handleSave(site.id, text)} />
            )
        } else {
            element = (
                <div>
                    <label onDoubleClick={this.handleEditActive.bind(this)}>
                        {site.text}
                    </label>
                    <button className="btn btn-sm btn-default"
                        onClick={this.handleEditActive.bind(this)}>编辑</button>
                    <button className="btn btn-sm btn-default"
                        onClick={() => deleteRefSite(site.id, gid)}>删除</button>
                </div>
            )
        }

        return (
            <li className={classnames({
                    editing: this.state.editing
                })}>
                {element}
            </li>
        )
    }
}

SiteItem.propTypes = {
    gid: PropTypes.number.isRequired,
    site: PropTypes.object.isRequired,
    editRefSite: PropTypes.func.isRequired,
    deleteRefSite: PropTypes.func.isRequired,
}

export default SiteItem
